package number_39;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    private List<List<Integer>> res;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        LinkedList<Integer> list = new LinkedList<>();
        backTrace(candidates, list, 0, target);

        return res;
    }

    private void backTrace(int[] candidates, LinkedList<Integer> list, int index,  int target) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] <= target) {
                list.addLast(candidates[i]);
                backTrace(candidates, list, i, target - candidates[i]);
                list.removeLast();
            }

        }
    }

    public static void main(String[] args) {
        new Solution().combinationSum(new int[] {2,3,5}, 8);

    }
}
